#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include "Log.hpp"

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " port[1024+]\n" << std::endl;
}

//./tcpclient serverip serverport
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(1);
    }

    //获取我们需要连接的服务器的ip和port
    std::string serverip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);
    
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    inet_pton(AF_INET,serverip.c_str(),&(server.sin_addr));

    while(true)
    {
        int cnt=5;
        int isreconnect=false;
        int sockfd=socket(AF_INET,SOCK_STREAM,0);
        if(sockfd<0)
        {
            std::cerr<<"socket error"<<std::endl;
            return 1;
        }

        do 
        {
            //客户端要绑定端口号，但是不需要显示bind，由操作系统随机选择
            //客户端发起connect的时候，进行自动随机bind
            int n=connect(sockfd,(struct sockaddr*)&server,sizeof(server));
            if(n<0)
            {
                isreconnect=true;
                cnt--;
                std::cerr<<"connect error... "<<std::endl;
                sleep(2);
            }
            else 
            {
                break;
            }
        }while(cnt&&isreconnect);

        if (cnt == 0)
        {
            std::cerr << "user offline..." << std::endl;
            break;
        }        
            
        std::string message;
        std::cout<<"Please Enter# ";
        std::getline(std::cin,message); //获取输入的信息

        int n=write(sockfd,message.c_str(),message.size()); //写入到套接字中
        if(n<0)
        {
            std::cerr<<"write error..."<<std::endl;
        }

        char inbuffer[4096];
        n=read(sockfd,inbuffer,sizeof(inbuffer)); //向套接字中读取数据 
        if(n>0)
        {
            inbuffer[n]=0;
            std::cout<<inbuffer<<std::endl;
        }

        close(sockfd);
    }
    return 0;
}